/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vng.survey.memcached;

import com.vng.zing.lib.Config;
import java.io.IOException;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;

/**
 *
 * @author namhh
 */
public class MyCache {

   private static final String NAMESPACE= "665a916cfa0ebe2e5cb957b85f46eeef";//md5(survey-project)
    private static MyCache instance = null;
    private MemcachedClient c = null;
  String address = Config.getParam("cached", "host") +":"+Config.getParam("cached", "port");
     
    private MyCache() {
        try {
           
            c =  new MemcachedClient(
                             new BinaryConnectionFactory(),
                 AddrUtil.getAddresses(address));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
     
    public static synchronized MyCache getInstance() {
      
        if(instance == null) {
            instance = new MyCache();
         }
         return instance;
    }
     
    public void set(String key, int ttl, final Object o) {
        key+=NAMESPACE;
        System.out.print(key);
//        getCache().set( key, ttl, o);
    }
     
    public Object get(String key) {
         key+=NAMESPACE;
        Object o = getCache().get(key);
//        if(o == null) {
//            System.out.println("Cache MISS for KEY: " + key);
//        } else {
//            System.out.println("Cache HIT for KEY: " + key);
//        }
        return o;
    }
     
    public Object delete(String key) {
        return getCache().delete( key); 
    }
     
     
   private MemcachedClient getCache() {
        try {     
            if( c == null ) {
                c = new MemcachedClient(new BinaryConnectionFactory(),
                     AddrUtil.getAddresses(address));
            }
            
        } catch(Exception e) {
             e.printStackTrace();
        }
        return c;
    }
}
